package dao;

import java.io.Serializable;
import java.util.List;

import tables.UserTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

import entity.User;

public class UserDao extends AbstractDao<UserTable, User> {

	public UserDao(final String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public void saveNew(final User newFlight) {
		// set ID
		newFlight.setId(getNextId());
		// get existing data
		final UserTable flightTable = deserializeFromXml();
		// add new row
		flightTable.getRows().add(newFlight);
		// save data
		serializeToXml(flightTable);
	}

	@Override
	public void update(final User entity) {
		// get existing data
		final UserTable flightTable = deserializeFromXml();
		// find by ID
		for (final User row : flightTable.getRows()) {
			if (row.getId().equals(entity.getId())) {
				// found!!!
				// copy data
				row.SetRoute(entity.GetRoute());
				row.SetTime(entity.GetTime());
				break;
			}
		}
		// save updated table
		serializeToXml(flightTable);
	}

	@Override
	public User get(final Serializable id) {
		// get existing data
		final UserTable circleTable = deserializeFromXml();
		// find by ID
		for (final User row : circleTable.getRows()) {
			if (row.getId().equals(id)) {
				return row;
			}
		}
		return null;
	}

	@Override
	public List<User> getAll() {
		// get existing data
		final UserTable flightTable = deserializeFromXml();
		return flightTable.getRows();
	}

	@Override
	public void delete(final Serializable id) {
		// get existing data
		final UserTable flightTable = deserializeFromXml();
		// find by ID
		User toBeDeleted = null;
		for (final User row : flightTable.getRows()) {
			if (row.getId().equals(id)) {
				// found!!!
				toBeDeleted = row;
				break;
			}
		}
		// remove from list
		flightTable.getRows().remove(toBeDeleted);
		// save updated table
		serializeToXml(flightTable);
	}

	@Override
	protected Class<UserTable> getTableClass() {
		return UserTable.class;
	}
}
